#include "../../include/offlinedict/MyLogger.h"
#include "../../include/offlinedict/Configuration.h"

#include "../../lib/log4cpp/PatternLayout.hh"
#include "../../lib/log4cpp/OstreamAppender.hh"
#include "../../lib/log4cpp/FileAppender.hh"
#include "../../lib/log4cpp/Priority.hh"

MyLogger *MyLogger::_pInstance = nullptr; // 懒汉式
pthread_once_t MyLogger::_once = PTHREAD_ONCE_INIT;

MyLogger *MyLogger::getInstance()
{
    pthread_once(&_once, init_r);
    return _pInstance;
}

void MyLogger::init_r()
{
    if (_pInstance == nullptr)
    {
        _pInstance = new MyLogger();
        atexit(destory);
    }
}

MyLogger::MyLogger()
: _mycat(Category::getRoot().getInstance("mylog"))
{
    // 日志布局：使用智能指针管理内存
    auto ptn1 = new PatternLayout();
    const string& patternLayout = Configuration::getInstance()->getMapValue("PATTERN_LAYOUT");
    if (patternLayout.empty())
    {
        cerr << "Error: PATTERN_LAYOUT is missing in the configuration!" << endl;
    }
    ptn1->setConversionPattern(patternLayout);

    auto ptn2 = new PatternLayout();
    ptn2->setConversionPattern(patternLayout);

    // 日志目的地
    auto pos = new OstreamAppender("console", &cout); // 输出到屏幕上
    pos->setLayout(ptn1);

    const string& logPath = Configuration::getInstance()->getMapValue("LOG_PATH");
    if (logPath.empty())
    {
        cerr << "Error: LOG_PATH is missing in the configuration!" << endl;
    }
    auto pfile = new FileAppender("file", logPath);  // 输出到文件
    pfile->setLayout(ptn2);

    // 设置优先级
    _mycat.setPriority(Priority::DEBUG);

    // 设置目的地
    _mycat.addAppender(pos);
    _mycat.addAppender(pfile);
}

MyLogger::~MyLogger()
{
    Category::shutdown();
}

void MyLogger::destory()
{
    if (_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}
